import axios from 'axios'
import {Message} from 'element-ui'
import store from '@/store'
import {server_base_url1, server_base_url2} from '@/common/config'
function getCookie(name)
{
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}

console.log(getCookie('name'));
export default function fetch(options) {
    return new Promise((resolve, reject) => {
        //创建一个axios实例
        let base = {
            one: server_base_url1,
            two: server_base_url2
        }
        const instance = axios.create({
            //设置默认根地址
            baseURL: base[options.base],
            //设置请求超时设置
            timeout: 2000,
            //设置请求时的header
            headers: {
                authorization: getCookie('name'),
            }
        })
        let must = {}

        function extend(target, source) {
            for (var obj in source) {
                target[obj] = source[obj];
            }
            return target;
        }

        if (options.must && options.params || options.must && options.data) {
            try {
                options.params = extend(options.params, must)
            } catch (e) {
                options.data = Object.assign(options.data, must)
            }
        } else {
            options.params = must
        }
        console.log(options);
        //请求处理
        instance(options).then((data) => {
            //请求成功时,根据业务判断状态
            resolve(data.data)
        })
            .catch((error) => {
                //请求失败时,根据业务判断状态
                if (error.response) {
                    let resError = error.response
                    let resCode = resError.status
                    let resMsg = error.message
                    Message.error('操作失败！错误原因 ' + resMsg)
                    reject({code: resCode, msg: resMsg})
                }
            })
    })
}
